<template>
  <div class="m-container">
    <el-row>
        <el-col :span="12" style="height: 200px;">
          <img :src="logo" class="logo" />
        </el-col>
        <el-col :span="10" class="text-right language" style="height: 200px;padding-top: 25px;">  
          <el-select v-model="language" placeholder="Select" size="large" style="width: 120px">
            <!-- <template #prefix><el-icon><Earth /></el-icon></template> -->
              <el-option label="简体中文" value="zh-CN" />
          </el-select>
        </el-col>
        <el-col :offset="15" :span="7">
          <el-card style="padding: 0 30px;">
            <h2>智箱界供应链平台</h2>
            <el-tabs v-model="activeName" class="tabs">
              <el-tab-pane label="密码" name="password">
                <el-form ref="loginRef" :model="loginForm" label-position="top" label-width="auto" hide-required-asterisk :rules="loginRules" class="login-form">
                  <el-form-item label="手机号/邮箱" label-position="top"  prop="username" class="hide-asterisk">
                    <el-input v-model="loginForm.username"/>
                  </el-form-item>
                  <el-form-item label="密码" label-position="top" prop="password" class="hide-asterisk">
                    <el-input v-model="loginForm.password" placeholder="请输入密码" show-password/>
                  </el-form-item>
                  <el-form-item>
                    <el-button :loading="loading" type="primary" class="submitBtn" @click.prevent="handleLogin"  >
                      <span v-if="!loading">登 录</span>
                      <span v-else>登 录 中...</span>
                    </el-button>
                  </el-form-item>
                </el-form>   
                <el-row>
                  <el-col :span="12">忘记密码？</el-col>
                  <el-col :span="12" class="text-right"><router-link class="link-type sign-in" :to="'/register'">立即注册</router-link></el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="验证码" name="code">
                <div style="height: 200px;text-align: center;">
                  功能开发中,请用账号&密码登录！
                </div>
              </el-tab-pane>
            </el-tabs>  
          </el-card>
        </el-col>
    </el-row>
    <div class="el-login-footer">
      <div>Copyright © 2025 河南陆海国际智能科技有限公司 版权所有 <a href="https://beian.miit.gov.cn/" target=_blank>豫ICP备2025122461号</a></div>
    </div>
  </div>
 
</template>

<script setup>
// import { Earth } from '@element-plus/icons-vue'
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserData } from '@/api/user/index'
import { classNameToArray } from "element-plus/es/utils/index.mjs";
import logo from '@/assets/logo/zxj-logo.png'
import { ref,onMounted,onUnmounted } from "vue";
import { useRoute, useRouter } from 'vue-router';

const activeName = ref('password') // password code
const language = ref('zh-CN')


const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: ""
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: ["change"], message: "请输入验证码" }]
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

watch(route, (newRoute) => {
  // console.log(newRoute)
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

function handleLogin () {
  proxy.$refs.loginRef.validate(valid => {
    if (Cookies.get("Admin-Token")){
      Cookies.remove("Admin-Token");
    }
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(async () => {
        localStorage.setItem('username', loginForm.value.username)
        router.push({ path: "/" });
        loading.value = false;
    
        const pathname = window.location.pathname
        Cookies.set('pathname',pathname)

      }).catch(() => {
        loading.value = false;
        Cookies.remove('pathname')
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode();
        }
      });
    }
  });
}

function getCode () {
  // getCodeImg().then(res => {
  //   captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
  //   if (captchaEnabled.value) {
  //     codeUrl.value = "data:image/gif;base64," + res.img;
  //     loginForm.value.uuid = res.uuid;
  //   }
  // });
}

function getCookie () {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

async function getUserInfo (id) {
  let userInfo = {}
  await getUserData(id).then(res => {
    userInfo = res.data
    // console.log(res)
  })
  return userInfo
}

getCode();
getCookie();

const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      handleLogin();
    }
};

onMounted(() => {
    window.addEventListener('keydown', handleKeyDown);
});
onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown);
  });
</script>

<style lang="scss" scoped>
.m-container{
  min-width: 1300px;
  min-height: 900px;
  height: 100%;
  background-image: url("../assets/images/login-background.png");
  background-size: cover;
  position: relative;
}
.logo{
  max-width: 150px;
  max-height: 100px;
  position: fixed;
  left: 3%;
  top: 5%;
}
.submitBtn{
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.el-login-footer {
    position: absolute;
    bottom: 20px;
    width: 100%;
    text-align: center;
    color: #614934;
    font-family: Arial;
    letter-spacing: 1px;
  }
  .m-container{
  :deep(.el-tabs__content) {
    color: #6b778c;
    font-size: 16px;
  }
  :deep(.el-tabs__item) {
    font-size: 16px;
  }
  :deep(.el-input__inner){
    height: 38px;
    font-size: 14px;
  }
  :deep(.el-form-item__label) {
    font-size: 14px;  /* 调整标签字体大小 */
  }
  :deep(input:-webkit-autofill),
  :deep(input:-webkit-autofill:hover), 
  :deep(input:-webkit-autofill:focus),
  :deep(input:-webkit-autofill:active) {
    -webkit-box-shadow: 0 0 0 1000px white inset !important; /* 用白色覆盖黄色背景 */
    transition: background-color 5000s ease-in-out 0s; /* 防止闪烁 */
  }
  :deep(.el-select__wrapper) {
    box-shadow: none !important;
    background-color: transparent !important;
    border: 1px solid transparent; /* 透明边框 */
    border-radius: 4px; /* 可选圆角 */
    transition: all 0.3s;
  }
}
.language{
  display: flex;
  justify-content: flex-end; /* 主轴上靠右对齐 */
  height: 40px;
  line-height: 40px;
  position: fixed;
  top: 20px;
  right: 10%;
  text-align: center;
  color: #2158F3;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.sign-in {
  float: right;
  color: #2158F3;

  font-weight: 700;
}
.logo-top{
  position: fixed;
  top: 50px;
  left: 100px;
}
.sidebar-logo{
  width: 107px;
}
</style>
